<template>
  <div class="ph48">
    <!-- <div class="tc-l2 mt24">设置此工资表模板参与计薪的统计项目，您可以新增或移除工资表模板的项目。</div> -->
    <div class="flex-center-between">
      <a-input-search v-model="keyword" placeholder="请输入工资项" style="width: 240px" />
      <a-button type="primary" @click="onAdd">
        <a-icon type="plus" />
        添加自定义统计项
      </a-button>
    </div>
    <div class="mt16">
      <a-table
        :scroll="{ x: true, y: true }"
        :dataSource="dataSourceNewFiltered"
        :columns="columns"
        :loading="loading"
        rowKey="id"
        size="middle"
      >
        <template slot="isOpen" slot-scope="text, record">
          <a-checkbox :disabled="!record.canClose" :checked="text" @change="onOpenChange($event, record.id)" />
        </template>
        <template slot="action" slot-scope="text, record">
          <a-space :size="12">
            <span v-if="record.canUpdate" class="pointer tc-theme" @click="onEdit(record)">编辑</span>
            <a-popconfirm
              v-if="record.canDelete"
              :title="`确认删除${record.name}吗，本用工单位中未归档的月工资表中该项将被同步删除并清空数据`"
              @confirm="doDelete(record.id)"
            >
              <span class="pointer tc-theme">删除</span>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </div>
    <div class="mt16 ta-center pb24">
      <a-space :size="24">
        <a-button @click="$emit('cancel')">取消</a-button>
        <a-button type="primary" @click="$emit('prev')">上一步</a-button>
        <a-button type="primary" @click="$emit('next')">下一步</a-button>
      </a-space>
    </div>
    <a-modal v-model="modalVisible" :title="modalTitle" @cancel="doCancel" @ok="doOk">
      <div>
        <span><i class="tc-red">*</i> 项目名称：</span>
        <a-input v-model="name" placeholder="请输入" style="width: 240px" />
      </div>
      <div class="mt16">
        <div class="flex-center-between">
          <div><i class="tc-red">*</i> 计算公式：</div>
          <a-space>
            <span>运算符：</span>
            <a-button class="ph6" style="height: 26px" @click="insertAtCursor('+')"
              ><i class="iconfont icon-jiahao" style="font-size: 12px"
            /></a-button>
            <a-button class="ph6" style="height: 26px" @click="insertAtCursor('-')"
              ><i class="iconfont icon-jianhao" style="font-size: 12px"
            /></a-button>
            <a-button class="ph6" style="height: 26px" @click="insertAtCursor('*')"
              ><i class="iconfont icon-chenghao" style="font-size: 12px"
            /></a-button>
            <a-button class="ph6" style="height: 26px" @click="insertAtCursor('/')"
              ><i class="iconfont icon-chuhao" style="font-size: 12px"
            /></a-button>
            <a-button class="ph6" style="height: 26px" @click="insertAtCursor('(')"
              ><i class="iconfont icon-zuokuohao" style="font-size: 12px"
            /></a-button>
            <a-button class="ph6" style="height: 26px" @click="insertAtCursor(')')"
              ><i class="iconfont icon-youkuohao" style="font-size: 12px"
            /></a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('%')">%</a-button>
            <a-button class="ph10" style="height: 26px" @click="insertAtCursor('.')">.</a-button>
          </a-space>
        </div>
        <div class="flex-center-between mt8">
          <div></div>
          <a-space>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('0')">0</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('1')">1</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('2')">2</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('3')">3</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('4')">4</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('5')">5</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('6')">6</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('7')">7</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('8')">8</a-button>
            <a-button class="ph8" style="height: 26px" @click="insertAtCursor('9')">9</a-button>
          </a-space>
        </div>
        <a-textarea
          v-model="statisticalFormula"
          id="textarea"
          placeholder="输入公式"
          class="br4 border p8 mt16"
          style="min-height: 160px; resize: none"
          @keydown="onKeydown"
        />
        <div class="flex mt16" style="width: 100%">
          <div style="width: 50%">
            <div class="title-block mb12">工资项</div>
            <div class="flex flex-wrap">
              <a-button
                v-for="item in wageItemLst"
                :key="item.name"
                size="small"
                class="fs12 mt8 mr8"
                @click="insertAtCursor(item.name, true)"
                >{{ item.name }}</a-button
              >
            </div>
          </div>
          <div style="width: 50%">
            <div class="title-block">统计项</div>
            <div class="flex flex-wrap">
              <a-button
                v-for="item in statItemLst"
                :key="item.name"
                size="small"
                class="fs12 mt8 mr8"
                @click="insertAtCursor(item.name, true)"
                >{{ item.name }}</a-button
              >
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script>
export default {
  name: "",
  components: {},
  mixins: [],
  props: {
    id: {
      type: String,
      default: ""
    },
    wageItemLst: {
      type: Array,
      default: () => []
    },
    statItemLst: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dataSource: [],
      columns: [
        { title: "统计项", dataIndex: "name", scopedSlots: { customRender: "name" } },
        { title: "计算公式", dataIndex: "statisticalFormula", scopedSlots: { customRender: "statisticalFormula" } },
        { title: "是否启用", dataIndex: "isOpen", width: 100, scopedSlots: { customRender: "isOpen" } },
        { title: "操作", dataIndex: "action", width: 100, scopedSlots: { customRender: "action" } }
      ],
      loading: false,
      modalVisible: false,
      modalTitle: "",
      name: "",
      statisticalFormula: "",
      currentItem: null,
      updateDict: {},
      keyword: ""
    };
  },
  computed: {
    dataSourceNew() {
      const lst = this.dataSource.map((item) => {
        return {
          ...item,
          isOpen: this.updateDict[item.id] === true || this.updateDict[item.id] === false ? this.updateDict[item.id] : item.isOpen
        };
      });
      return lst;
    },
    dataSourceNewFiltered() {
      return this.dataSourceNew.filter((item) => item.name.indexOf(this.keyword) >= 0);
    }
  },
  watch: {
    id: {
      handler(newVal) {
        if (newVal) {
          this.loadData();
        }
      },
      immediate: true
    },
    dataSourceNew: {
      handler(newVal) {
        this.$emit(
          "update:statItemLst",
          newVal.filter((item) => item.isOpen)
        );
      },
      deep: true,
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    doDelete(templateCovarianceItemId) {
      this.$request({
        url: `/salary/api/v1/templateCovarianceItems/${templateCovarianceItemId}`,
        method: "delete"
      })
        .then((res) => {
          this.$message.success("删除成功");
          this.loadData();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onKeydown(e) {
      if (!["ArrowLeft", "ArrowRight", "Backspace"].includes(e.key)) {
        e.preventDefault();
      }
    },
    async insertAtCursor(val, needSymbol) {
      const newVal = needSymbol ? `#${val}#` : val;
      const box = document.querySelector("#textarea");
      if (box.selectionStart || box.selectionStart === 0) {
        var startPos = box.selectionStart;
        var endPos = box.selectionEnd;
        this.statisticalFormula = box.value.substring(0, startPos) + newVal + box.value.substring(endPos, box.value.length);
        await this.$nextTick(); // 这里是重点
        box.focus();
        box.setSelectionRange(endPos + newVal.length, endPos + newVal.length);
      } else {
        this.statisticalFormula += newVal;
      }
    },
    onOpenChange(evt, id) {
      this.updateDict = {
        ...this.updateDict,
        [`${id}`]: evt.target.checked
      };
    },
    doCancel() {
      this.modalVisible = false;
      this.modalTitle = "";
      this.name = "";
      this.statisticalFormula = "";
      this.currentItem = null;
    },
    doOk() {
      if (!this.name || !this.statisticalFormula) {
        this.$message.warning("内容未填写");
        return false;
      }
      if (this.currentItem) {
        this.$request({
          url: `/salary/api/v1/templateCovarianceItems`,
          method: "put",
          data: {
            salaryTemplateId: this.id,
            id: this.currentItem.id,
            name: this.name,
            statisticalFormula: this.statisticalFormula
          }
        })
          .then((res) => {
            this.$message.success("修改成功");
            this.loadData();
            this.doCancel();
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$request({
          url: `/salary/api/v1/templateCovarianceItems`,
          method: "post",
          data: {
            salaryTemplateId: this.id,
            name: this.name,
            statisticalFormula: this.statisticalFormula
          }
        })
          .then((res) => {
            this.$message.success("添加成功");
            this.loadData();
            this.doCancel();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    onAdd() {
      this.modalTitle = "添加统计项";
      this.name = "";
      this.statisticalFormula = "";
      setTimeout(() => {
        this.modalVisible = true;
      }, 0);
    },
    onEdit(record) {
      this.modalTitle = "编辑统计项";
      this.name = record.name;
      this.statisticalFormula = record.statisticalFormula;
      this.currentItem = record;
      setTimeout(() => {
        this.modalVisible = true;
      }, 0);
    },
    loadData() {
      this.loading = true;
      this.$request({
        url: `/salary/api/v1/templateCovarianceItems/selectBySalaryTemplateId`,
        params: {
          salaryTemplateId: this.id
        }
      })
        .then((res) => {
          this.dataSource = res.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    }
  }
};
</script>
<style lang="scss"></style>
